import { getToken } from '@/utils/storage'
import Article from '@/views/Article.vue'
import Collect from '@/views/Collect.vue'
import Detail from '@/views/Detail.vue'
import Layout from '@/views/Layout.vue'
import Like from '@/views/Like.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import User from '@/views/User.vue'
import { Toast } from 'vant'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/article',
    children: [
      {
        path: 'article',
        component: Article
      },
      {
        path: 'like',
        component: Like
      },
      {
        path: 'collect',
        component: Collect
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/detail/:id',
    component: Detail
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/register',
    component: Register
  }
]

const router = new VueRouter({
  routes
})

// 白名单
const WHITE_LIST = ['/login', '/register']

// 全局前置守卫的语法：路由实例.beforeEach(to, from, next){}
router.beforeEach((to, from, next) => {
  // to: 即将进入的路由对象
  // from: 即将离开的路由对象
  // next: 放行函数
  // next()
  // next('/login')
  // next(false)
  // next({ path: '/login' })
  // next(error)
  console.log(to, from)// 打印路由信息
  next()// 放行
  // 如果已经登录，则正常跳转，若未登录，则跳转到登录页
  if (getToken()) {
    // 如果有登录，即有token，则直接放行，next中不加任何参数，跳转到前往的页面
    next()
  } else if (WHITE_LIST.includes(to.path)) {
    // 若未登录，但用户本身要跳到白名单页面（例如登录页、注册页），也直接放行即可
    next()
  } else {
    // 若未登录，但用户要跳到其他页面，则提示用户登录，并跳转到登录页
    Toast.fail('请先登录')
    next('/login')
  }
})

export default router
